package com.hlkj.baojin.constant.global_exception;

import com.alibaba.fastjson.JSONObject;
import com.hlkj.baojin.utils.bean.JsonResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.util.Enumeration;

/**
 * 一：在进入Controller之前，譬如请求一个不存在的地址，404错误。
 * 二：在执行@RequestMapping时，进入逻辑处理阶段前。譬如传的参数类型错误。
 * 三：以上都正常时，在controller里执行逻辑代码时出的异常。譬如NullPointerException。
 * Created by lzx on 18/3/31.
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    private static Logger logger = LogManager.getLogger(GlobalExceptionHandler.class.getName());


    /**
     * 在controller里面内容执行之前，校验一些参数不匹配啊，Get post方法不对啊之类的
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return ResponseEntity.ok(JsonResult.error(status.value(), "参数名称不匹配 或者 请求方法不对 -----》" + ex.getLocalizedMessage()));
    }

    /** 捕捉正常程序抛出的异常，给前端提示
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = {IllegalArgumentException.class, ValidationException.class})
    @ResponseBody
    public ResponseEntity<String> jsonHandlerTips(HttpServletRequest request, Exception e) {
        log(e, request);
        String message = e.getMessage();
        String json = JSONObject.toJSONString(JsonResult.error(500, StringUtils.isEmpty(message)?"":message));
        return ResponseEntity.ok(json);
    }

    /**
     * 逻辑抛异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<JsonResult> jsonHandler(HttpServletRequest request, Exception e) {
        log(e, request);
        return ResponseEntity.ok(JsonResult.error(500, "未知异常"));
    }


    private void log(Exception ex, HttpServletRequest request) {
        logger.error("************************异常开始*******************************");
//        if(getUser() != null)
//            logger.error("当前用户id是" + getUser().getUserId());
        logger.error(ex);
        logger.error("请求地址：" + request.getRequestURL());
        Enumeration enumeration = request.getParameterNames();
        logger.error("请求参数");
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement().toString();
            logger.error(name + "---" + request.getParameter(name));
        }

        StackTraceElement[] error = ex.getStackTrace();
        for (StackTraceElement stackTraceElement : error) {
            logger.error(stackTraceElement.toString());
        }
        logger.error("************************异常结束*******************************");
    }
}